<template>
  <div class="app-container">
    <div style="font-size: 25px;">修改采购订单</div>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="采购单号" prop="poNo">
            <el-input v-model="pono" placeholder="请输入采购单号" style="width: 230px;" oninput="value=value.replace(/[^\d\w]/g,'')" maxlength="25"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" @change="suppliername" style="width: 230px;">
              <el-option
                v-for="dict in supplierlist"
                :key="dict.id"
                :label="dict.supplierName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款方式" prop="paymentType">
            <el-select v-model="form.paymentType" placeholder="请选择付款方式" style="width: 230px;">
              <el-option
                v-for="dict in dict.type.erp_payment_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商联系人" prop="supplieruser">
            <el-input v-model="supplieruser" placeholder="请输入供应商联系人" style="width: 230px;" maxlength="25"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商手机号" prop="supplierphone">
            <el-input v-model="supplierphone"
                      placeholder="请输入供应商手机号"
                      style="width: 230px;"
                      maxlength="15"
                      @input="v => supplierphone = v.replace(/[^\d]/g,'')"/>
          </el-form-item>
        </el-col>
      </el-row>
<!--      <el-form-item label="入库类型" prop="warehousingType" v-show="false">
        <el-input v-model="form.warehousingType = 1" placeholder="请输入入库类型" style="width: 230px;"/>
      </el-form-item>-->
      <el-form-item label="退货状态" prop="returnGoods" v-show="false">
        <el-input v-model="form.returnGoods = 1" placeholder="请输入退货状态" style="width: 230px;"/>
      </el-form-item>
      <el-form-item label="审核类型" prop="processType" v-show="false">
        <el-input v-model="form.processType = 1" placeholder="请输入审核类型" style="width: 230px;"/>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"  style="width: 85%" maxlength="250"/>
      </el-form-item>
    </el-form>
    <!--横线组件纯纯为了页面好看-->
    <el-divider></el-divider>
    <el-row style="margin-bottom: 20px;">
      <el-col :span="1.5">
        <div style="font-size: 20px; margin-top: 5px">采购商品</div>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加商品</el-button>
      </el-col>
    </el-row>
    <el-table :data="addGoodsList" show-summary :summary-method="getSummaries">
<!--      <el-table-column type="selection" width="80" align="center"/>-->
      <el-table-column label="商品ID" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="采购单价" align="center" prop="monovalent">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.monovalent" placeholder="请输入价格" size="mini" style="width:100px"
                    @input="handleEdit(scope.$index, scope.row)"
                    maxlength="10"
                    @keyup.native="scope.row.monovalent = scope.row.monovalent = scope.row.monovalent.replace(/[^\d.]/g,'');
                                   scope.row.monovalent = scope.row.monovalent.replace(/\.{2,}/g,'.');
                                   scope.row.monovalent = scope.row.monovalent.replace(/^\./g,'');
                                   scope.row.monovalent = scope.row.monovalent.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                   scope.row.monovalent = scope.row.monovalent.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
          ></el-input>
        </div>
      </el-table-column>
      <el-table-column label="采购数量" align="center" prop="quantity">
        <div class="item" slot-scope="scope">
          <el-input-number v-model="scope.row.quantity" oninput="value=value.replace(/[^0-9.]/g,'')" controls-position="right" :min="1" size="mini" style="width:100px"  @input="handleEdit(scope.$index, scope.row)"/>
        </div>
      </el-table-column>
      <el-table-column label="采购总价" align="center" prop="total">
        <div class="item" slot-scope="scope">
          <el-input class="item__input" v-model="scope.row.total" placeholder="销售总价" size="mini" style="width:100px" readonly="readonly"></el-input>
        </div>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="deleteGoodsList(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >删除商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitForm">保存采购订单</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>

  <!--选择商品信息弹出框-->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body :close-on-click-modal = "false">
      <el-form :model="queryParamsGoods" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParamsGoods.name"
            placeholder="请输入商品名称"
            clearable
            maxlength="35"
            @keyup.enter.native="handleQueryGoods"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
            v-model="queryParamsGoods.brandId"
            placeholder="请选择品牌"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQueryGoods"
          >
            <el-option
              v-for="dict in brandList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上下架" prop="shelves">
          <el-select
            v-model="queryParamsGoods.shelves"
            placeholder="请输入上下架"
            clearable
            @keyup.enter.native="handleQueryGoods"
          >
            <el-option label="上架" value=1 />
            <el-option label="下架" value=0 />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <treeselect v-model="queryParamsGoods.categoryId" :options="categoryOptions" :normalizer="normalizer"
                      placeholder="选择分类"
                      style="width: 230px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryGoods">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column label="商品ID" align="center" prop="id"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="分类" align="center" prop="categoryName"/>
        <el-table-column label="品牌" align="center" prop="brandName"/>
        <el-table-column label="单位" align="center" prop="companyName"/>
        <el-table-column label="库存" align="center" prop="inventory"/>
        <el-table-column label="成本单价" align="center" prop="cost"/>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="addGood(scope.row)"
              v-hasPermi="['system:goods:edit']"
            >添加商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParamsGoods.pageNum"
        :limit.sync="queryParamsGoods.pageSize"
        @pagination="getGoodsList"
      />
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button @click="cancelGoods">关闭页面</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/erp/purchase";
import {getSupplier, listSupplier} from "@/api/erp/supplier";
import {getGoods, listGoods, listGoodsPurchase} from "@/api/erp/goods";
import {getPurchaseoods, listPurchaseoodsInfo} from "@/api/erp/purchaseGoods";
import {listBrand} from "@/api/erp/brand";
import {listCategory} from "@/api/erp/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "edit",
  components: {Treeselect},
  dicts: ['erp_warehousing_type', 'erp_return_goods', 'erp_process_type', 'erp_payment_type'],
  data() {
    return {
      //修改页面根据id查询信息
      purchaseId:null,
      monovalent:null,
      //随机生成的订单编号
      pono:"",
      supplieruser:"",
      supplierphone:"",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      purchaseList: [],
      //品牌列表
      brandList: [],
      //分类列表
      categoryOptions: [],
      //供应商数据
      supplierlist: [],
      // 商品信息表格数据
      goodsList: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        poNo: null,
        goodsIds: null,
        supplierId: null,
        supplieruser: null,
        supplierphone: null,
        paymentType: null,
        warehousingType: null,
        returnGoods: null,
        processType: null,
        createUser: null,
        gettime:"",
        //采购单价
        monovalents: "",
        //采购数量
        quantitys: "",
        //采购总价
        totalPrices: "",

      },
      // 选择商品查询参数
      queryParamsGoods: {
        pageNum: 1,
        pageSize: 10,
        goodsIds: null,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
      },
      //修改商品查询数据
      queryParamsPurchaseGoods:{
        purchaseId:null,
      },
      //供应商查询参数
      queryParamsSupplier: {
        pageNum: 1,
        pageSize: 10,
        supplierName: null,
        supplierContacts: null,
        supplierPhone: null,
        supplierCategory: null,
        supplierAddress: null,
        supplierBank: null,
        supplierBankAccount: null,
        supplierDutyParagraph: null,
        detailedAddress: null,
        remarks: null,
        creatTime: null,
        creatUser: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    //获取修改按钮带过来的id
    const purchaseId = this.$route.query.id
    //将id赋值
    this.purchaseId  = purchaseId;
    if (purchaseId){
      this.getList(purchaseId);
    }
    //查询修改关联商品数据
    if (purchaseId){
      this.getPurchaseGoods(purchaseId);
    }
    //查询添加商品表方法
    this.getGoodsList();
    //查询供应商列表方法
    this.getSupplierlist();
  },
  methods: {
    //查询供应商方法
    getSupplierlist(){
      listSupplier(this.queryParamsSupplier).then(response => {
        this.supplierlist = response.rows;
      });
    },
    /*选择供应商时的监听*/
    suppliername(val){
      const id = val
      getSupplier(id).then(response => {
        this.supplieruser = response.data.supplierContacts
        this.supplierphone = response.data.supplierPhone

      });
    },
    /** 查询商品列表 */
    getGoodsList() {
      this.loading = true;
      listGoodsPurchase(this.queryParamsGoods).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //单个添加商品方法
    addGood(row) {
      for (var i = 0; i < this.addGoodsList.length; i++) {
        let newVar = this.addGoodsList[i];
        //这里Number(newVar.id)是因为newVar.id变成了string类型需要转换一下
        if (row.id === Number(newVar.id)) {
          this.$modal.alertError("以添加过此商品!");
          return;
        }
      }
      this.addGoodsList.push(row);
    },
    //多选添加商品方法
    addGoodList(row) {
      const ids = row.id || this.ids;
      ids.forEach((item,index)=>{
        getGoods(item).then(response => {
          this.addGoodsList.push(response.data);
        });
      })
    },



    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },

    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "total"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    //node分类节点
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    //商品总价计算
    handleEdit(index, row) {
      if(row.quantity && row.monovalent){
        row.total = parseFloat(Number(row.quantity)*Number(row.monovalent)).toFixed(2)
      }
    },
    /** 查询修改采购订单列表 */
    getList(puchaseId) {
      //查询详情
      getPurchase(puchaseId).then(response => {
        this.form = response.data;
        this.pono = response.data.poNo
        this.supplieruser = response.data.supplieruser
        this.supplierphone = response.data.supplierphone
      });
    },
    /*查询修改关联商品数据*/
    getPurchaseGoods(puchaseId){
      this.queryParamsPurchaseGoods.purchaseId = puchaseId
      listPurchaseoodsInfo(this.queryParamsPurchaseGoods).then(response => {
        this.addGoodsList = response.rows
        for (let i = 0; i < this.addGoodsList.length ; i++) {
          this.addGoodsList[i].id = response.rows[i].goodsNumber
          this.addGoodsList[i].name = response.rows[i].goodsName
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$router.push({path: '/purchase/purchase'});
    },
    //采购商品列表取消按钮
    cancelGoods() {
      this.open = false;
      this.resetGoods();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        poNo: null,
        supplierId: null,
        paymentType: null,
        warehousingType: null,
        returnGoods: null,
        supplieruser: null,
        supplierphone: null,
        processType: null,
        createTime: null,
        updateTime: null,
        createUser: null
      };
      this.resetForm("form");
    },
    // 添加商品表单重置
    resetGoods() {
      this.formGoods = {
        id: null,
        name: null,
        thumbnail: null,
        banners: null,
        description: null,
        sortDescription: null,
        price: null,
        brandId: null,
        categoryId: null,
        cost: null,
        type: null,
        details: null,
        labels: null,
        inventory: null,
        sales: null,
        weight: null,
        supplierId: null,
        shelves: null,
        shopId: null,
        sort: null,
        createTy: null,
        updateTime: null,
        createTime: null,
        barCode: null,
        speclist: null,
        speclabellist: null
      };
      this.resetForm("formGoods");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /*商品搜索按钮*/
    handleQueryGoods() {
      this.queryParamsGoods.pageNum = 1;
      this.getGoodsList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQueryGoods();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增采购商品按钮操作 */
    handleAdd() {
      this.getBrandList();
      this.getCategoryList();
      this.open = true;
      this.title = "选择商品";
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 新增提交按钮 */
    submitForm() {
     // 判断是否填写采购单号
      if(this.pono === ""){
        this.$modal.msgError("请填写采购单号");
        return;
      }
      // 判断是否选择供应商
      if(this.form.supplierId === undefined){
        this.$modal.msgError("请选择供应商");
        return;
      }
      //判断是否选择付款方式
      if(this.form.paymentType === undefined){
        this.$modal.msgError("请选择付款方式");
        return;
      }
      //判断是否填写供应商联系人
      if(this.supplieruser === ""){
        this.$modal.msgError("请填写供应商联系人");
        return;
      }
      //判断是否填写供供应商手机号
      if(this.supplierphone === ""){
        this.$modal.msgError("请填写供应商手机号");
        return;
      }
     //判断是否添加商品
     if(this.addGoodsList.length === 0){
       this.$modal.msgError("请添加商品");
       return;
     }
      if(this.addGoodsList.length !== 0){
        for (let i = 0; i < this.addGoodsList.length; i++) {
          if (this.addGoodsList[i].monovalent === null || this.addGoodsList[i].monovalent === ""){
            this.$modal.msgError("请填写采购单价");
            return;
          }
          if (this.addGoodsList[i].quantity === null || this.addGoodsList[i].quantity === undefined){
            this.$modal.msgError("请填写采购数量");
            return;
          }
          if (this.addGoodsList[i].quantity <= 0 ){
            this.$modal.msgError("请填写正确的采购数量");
            return;
          }
        }
      }
     //商品id数组
     let goodsId = [];
     //采购单价数组
     let monovalent = [];
     //采购数量数组
     let quantity = [];
     //采购总价数组
     let totalPrice = [];
     for (let i = 0; i < this.addGoodsList.length; i++) {
       //获得商品id
       goodsId.push(this.addGoodsList[i].id)
       //获得采购单价
       monovalent.push(this.addGoodsList[i].monovalent)
       //获得采购数量
       quantity.push(this.addGoodsList[i].quantity)
       //获得采购总价
       totalPrice.push(this.addGoodsList[i].total)
     }
     //将获得的商品id以数组的形式传到后台
     this.form.goodsIds = goodsId;
     //将获得的采购单价以数组的形式传到后台
     this.form.monovalents = monovalent;
     //将获得的采购数量以数组的形式传到后台
     this.form.quantitys = quantity;
     //将获得的采购总价以数组的形式传到后台
     this.form.totalPrices = totalPrice;
     //将采购订单传回后台
     this.form.poNo = this.pono
     //将供应商联系人传回后台
     this.form.supplieruser = this.supplieruser
     //将供应商手机号传回后台
     this.form.supplierphone = this.supplierphone
     //获取修改数据id
     this.form.id = this.$route.query.id
     //调取修改接口
     updatePurchase(this.form).then(response => {
       if (response.code === 200) {
         this.$modal.msgSuccess("修改成功");
         this.open = false;
         this.cancel();
       }
     });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>

</style>
